/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sigodonto.model.util;

import br.com.sigodonto.view.managedbean.EmitirReceituarioMB;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.FacesContext;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Fidelis
 */
public class RelatorioUtil {

    public static void gerarRelatorio(String relatorio, Map<String, Object> parameters, List colecao) {

//        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(prescrevidos);
//        String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/relatorios/receituario.jasper");
//        HashMap<String, Object> parameterMap = new HashMap<String, Object>();
//        String nomepaciente = this.pacienteSelecionado.getNome() + this.pacienteSelecionado.getSobrenome();
//        String enderecoClinica = this.clinica.getEndereco().getLogradouro() + ", " + this.clinica.getEndereco().getNumero() + " - " + this.clinica.getEndereco().getBairro() + ", " + this.clinica.getEndereco().getCidade() + "-" + this.clinica.getEndereco().getUf();
//        parameterMap.put("NOME_PACIENTE", nomepaciente);
//        parameterMap.put("CLINICA_ENDERECO", enderecoClinica);
//        parameterMap.put("CLINICA_EMAIL", this.clinica.getContato().getEmail());
//        parameterMap.put("CLINICA_TELEFONE", this.clinica.getContato().getTelefone());
//
//        JasperPrint jasperPrint;
//        System.out.println("AQUIIIIIIIIIIIII2");
//        try {
//            jasperPrint = JasperFillManager.fillReport(reportPath, parameterMap, beanCollectionDataSource);
//            System.out.println("AQUIIIIIIIIIIIII3");
//            HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
//            httpServletResponse.addHeader("Content-disposition", "attachment; filename=receituario.pdf");
//            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
//            JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
//            System.out.println("AQUIIIIIIIIIIIII4");
//            FacesContext.getCurrentInstance().responseComplete();
//            System.out.println("AQUIIIIIIIIIIIII5");
//        } catch (JRException ex) {
//            Logger.getLogger(EmitirReceituarioMB.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(EmitirReceituarioMB.class.getName()).log(Level.SEVERE, null, ex);
//        }


//        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(prescrevidos);
//        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
//        try {
//            try {
//                ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
////                String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/relatorios/receituario.jasper");
//                String caminho = "/resources/relatorios/";
//                String relatorio = caminho + "receituario.jasper";
//                InputStream reportStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(relatorio);
//
//                HashMap<String, Object> parameterMap = new HashMap<String, Object>();
//                String nomepaciente = this.pacienteSelecionado.getNome() + this.pacienteSelecionado.getSobrenome();
//                String enderecoClinica = this.clinica.getEndereco().getLogradouro() + ", " + this.clinica.getEndereco().getNumero() + " - " + this.clinica.getEndereco().getBairro() + ", " + this.clinica.getEndereco().getCidade() + "-" + this.clinica.getEndereco().getUf();
//                parameterMap.put("NOME_PACIENTE", nomepaciente);
//                parameterMap.put("CLINICA_ENDERECO", enderecoClinica);
//                parameterMap.put("CLINICA_EMAIL", this.clinica.getContato().getEmail());
//                parameterMap.put("CLINICA_TELEFONE", this.clinica.getContato().getTelefone());
//                JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream, parameterMap, beanCollectionDataSource);
//
//                httpServletResponse.setContentType("application/pdf");
//                servletOutputStream.flush();
//                servletOutputStream.close();
//            } catch (JRException ex) {
//                Logger.getLogger(EmitirReceituarioMB.class.getName()).log(Level.SEVERE, null, ex);
//            }
//        } catch (IOException ex) {
//            Logger.getLogger(EmitirReceituarioMB.class.getName()).log(Level.SEVERE, null, ex);
//        }

        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(colecao);
        String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/relatorios/" + relatorio);

        JasperPrint impressao;
        try {
            impressao = JasperFillManager.fillReport(reportPath, parameters, beanCollectionDataSource);

            JasperViewer viewer = new JasperViewer(impressao, false);
            viewer.setVisible(true);

//            FacesContext context = FacesContext.getCurrentInstance();
//            servletContext = (ServletContext) context.getExternalContext().getContext();
//
//            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
//            // Configura o response para suportar o relatório
//            response.setContentType("application/pdf");
//            // response.addHeader("Content-disposition", "inline; filename=\"arquivo.pdf\"");
//            response.addHeader("Content-disposition", "attachment; filename=\"arquivo.pdf\"");
//
//            // Preenche o relatório com os parametros e o data source
//            impressao = JasperFillManager.fillReport(reportPath, parameterMap, beanCollectionDataSource);
//
//            // Exporta o relatório
//            JasperExportManager.exportReportToPdfStream(impressao, response.getOutputStream());
//
//            // Salva o estado da aplicação no contexto do JSF
////            context.getApplication().getStateManager().saveView(context);
//            // Fecha o stream do response
////            context.responseComplete();
//
//            this.redirect("emitirReceituario.xhtml");
//            FacesContext context = FacesContext.getCurrentInstance();
//
//            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
//            response.setContentType("application/pdf");
//            ServletOutputStream ouputStream;
//
//            ouputStream = response.getOutputStream();
//
//
//            JRExporter exporter = new JRPdfExporter();
//            exporter.setParameter(JRExporterParameter.JASPER_PRINT, impressao);
//
//            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
//            exporter.exportReport();
//
//            context.responseComplete();
        } catch (JRException ex) {
            Logger.getLogger(EmitirReceituarioMB.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static void gerarRelatorioSemColecao(String relatorio, Map<String, Object> parameters) {
        String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/relatorios/" + relatorio);

        JasperPrint impressao;
        try {
            impressao = JasperFillManager.fillReport(reportPath, parameters, new JREmptyDataSource());

            JasperViewer viewer = new JasperViewer(impressao, false);
            viewer.setVisible(true);
        } catch (JRException ex) {
            Logger.getLogger(EmitirReceituarioMB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
